package com.compass.doctor.ui.home.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnDialogBottomClick
import com.compass.doctor.callback.OnRefusalButtonClick
import com.compass.doctor.databinding.FragmentBaseListBinding
import com.compass.doctor.dialog.ChoosePhoneDialog
import com.compass.doctor.dialog.FinishInquiryDialog
import com.compass.doctor.dialog.InquiryOrderDialog
import com.compass.doctor.dialog.RefusalDialog
import com.compass.doctor.ui.home.DoctorListActivity
import com.compass.doctor.ui.home.adapter.InquiryOrderAdapter
import com.compass.doctor.ui.home.viewmodel.InquiryOrderViewModel
import com.compass.doctor.ui.mine.CaSignatureActivity
import com.compass.doctor.ui.patient.PatientChatActivity
import com.compass.doctor.ui.patient.PractitionerToPatientChatActivity
import com.compass.doctor.ui.patient.VideoCallActivity
import com.compass.doctor.ui.prescription.PrescriptionTypeActivity
import com.compass.framework.R
import com.compass.framework.constant.CLINICAL_RECEPTION
import com.compass.framework.constant.KEY_ORDER_TYPE
import com.compass.framework.constant.REFUSE_RECEPTION
import com.compass.framework.constant.SET_INDEX
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.visible
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.InquiryMessage
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.netease.lava.nertc.sdk.NERtcEx
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description： 问诊单Fragment
 * Date:2023/12/12 9:43
 */
class InquiryOrderFragment : BaseVBFragment<FragmentBaseListBinding>(), OnLoadMoreListener,
    OnRefreshListener {

    private val inquiryOrderViewModel: InquiryOrderViewModel by viewModels()
    private lateinit var mAdapter: InquiryOrderAdapter
    private var mPage = 1
    private var orderType: Int = 1//1-待接诊 2-已接诊 3-已完成 可不传所有
    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            orderType = it.getInt(KEY_ORDER_TYPE)
        }
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mBinding?.refreshLayout?.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@InquiryOrderFragment)
            setOnLoadMoreListener(this@InquiryOrderFragment)
        }
        mAdapter = InquiryOrderAdapter(orderType)
        val dp10 = dpToPx(10)
        mBinding?.recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(left = dp10, top = dp10, right = dp10, bottom = dp10)
                setLastBottom(true)
            })
            adapter = mAdapter
        }
        mAdapter.setBottomCallBack(onBottomClick)

    }

    /**
     * 判断是否有权限
     */
    private fun havePermission(account: String, orderId: String) {
        //判断是否有权限
        if (XXPermissions.isGranted(
                requireContext(),
                Permission.RECORD_AUDIO,
                Permission.CAMERA
            )
        ) {
            requestPermission(account,orderId)

        } else {
            CommonMessageDialog.Builder(requireActivity())
                .setTitle(getStringFromResource(com.compass.doctor.R.string.permission_explain))
                .setMessage(getStringFromResource(com.compass.doctor.R.string.video_permission_logs))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermission(account,orderId)
                    it?.dismiss()
                }.create().show()
        }
    }


    /**
     * 请求权限
     */
    private fun requestPermission(account: String, orderId: String) {
        XXPermissions.with(this)
            //小米应用市场不允许提前获取相册拍照权限，这里先获取存储权限，进入到相册选择页面点击拍照按钮时在获取拍照权限
            .permission(Permission.RECORD_AUDIO)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips(com.compass.doctor.R.string.default_agree_permission)
                        return
                    }
                    VideoCallActivity.start(requireContext(),account,orderId)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    TipsToast.showTips(com.compass.doctor.R.string.default_agree_permission)
                }
            })
    }


    private var onRefusalBottomClick = object : OnRefusalButtonClick {
        override fun onButtonCallBack(orderId: String, msg: String) {
            showLoading()
            inquiryOrderViewModel.clinicalReception(orderId, 2, msg)

        }

    }

    private var onBottomClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            val item = mAdapter.getItem(position)
            item?.let { order ->
                when (msgType) {
                    "Refusal" -> {
                        //拒诊
                        RefusalDialog.Builder(requireActivity(), order.id, onRefusalBottomClick)
                            .show()
                    }

                    "Treatment" -> {
                        //转诊
                        DoctorListActivity.start(requireContext(), 2, order.id)
                    }

                    "Reception" -> {
                        //接诊操作
                        if (UserInfoManager.isCASignature()) {
                            InquiryOrderDialog.Builder(
                                requireActivity(),
                                order.id,
                                onDialogBottomClick
                            ).show()
                        } else {
                            CaSignatureActivity.start(requireContext())
                        }
                    }

                    "callPatient" -> {



                        callPhone(order.id,UserInfoManager.getUserInfo()?.mobile,UserInfoManager.getUserInfo()?.alternativeMobile)
                    }

                    "details" -> {

                        goToChat( UserInfo(
                            order.patientWyyxAccid,
                            order.patientName,
                            order.patientAvatar
                        ), order.patientId )


//                        ChatUtils.startVideoCall(context, "1709603162725")
                    }

                    "video" -> {
//                        havePermission(order.patientWyyxAccid,order.id)
                        //这里改为处方 不呼叫了
                        PrescriptionTypeActivity.start(requireContext(),UserInfo(
                            order.patientWyyxAccid,
                            order.patientName,
                            order.patientAvatar
                        ),
                            order.patientId,
                            "")
//                        ChatUtils.startVideoCall(context, order.patientWyyxAccid)
                    }

                    "records" -> {

                        goToChat( UserInfo(
                                order.patientWyyxAccid,
                                order.patientName,
                                order.patientAvatar
                            ), order.patientId )


//                        showToast("开发中")
                    }

                    "checkout" -> {
                        //结束问诊
                        showLoading()
                        inquiryOrderViewModel.finishInterrogation(order.id, null)
//                        FinishInquiryDialog.Builder(
//                            requireActivity(),
//                            1,
//                            object : OnCustomButtonClick {
//                                override fun onButtonCallBack(codeType: Int, msg: String?) {
//                                    if (!msg.isNullOrEmpty()) {
//
//                                        showLoading()
//                                        inquiryOrderViewModel.retreatOrder(order.id, msg)
//                                    } else {
//                                        showToast("请输入退诊原因")
//                                    }
//                                }
//                            }).show()


                    }

                    else -> {}
                }
            }

        }
    }

    private fun goToChat(userInfo: UserInfo, patientId: String) {
        if (UserInfoManager.getUserType() == "1") {
            PatientChatActivity.start(
                requireContext(),
                userInfo,
                patientId
            )
        } else {
            PractitionerToPatientChatActivity.start(
                requireContext(),
                userInfo,
                patientId
            )
        }
    }

    private var inquiry: InquiryMessage? = null
    private var onDialogBottomClick = object : OnDialogBottomClick {
        override fun onDialogButtonCallBack(inquiryMessage: InquiryMessage, msgType: String) {
            inquiry = inquiryMessage
            when (msgType) {
                "Refusal" -> {
                    //拒诊
                    RefusalDialog.Builder(
                        requireActivity(),
                        inquiryMessage.orderId,
                        onRefusalBottomClick
                    ).show()
                }

                "Treatment" -> {
                    //转诊
                    DoctorListActivity.start(requireContext(), 2, inquiryMessage.orderId)
                }

                "Reception" -> {
                    //接诊操作
                    if (UserInfoManager.isCASignature()) {
                        showLoading()
                        inquiryOrderViewModel.clinicalReception(inquiryMessage.orderId, 1)
                    } else {
                        CaSignatureActivity.start(requireContext())
                    }

                }

            }
        }
    }

    private fun callPhone(id: String,   mainNumber: String?, assistantNumber: String?) {
        ChoosePhoneDialog.Builder(requireActivity(),mainNumber,assistantNumber).setOnNumberChooseCall { s, i ->

            CommonMessageDialog.Builder(requireActivity())
                .setTitle(getStringFromResource(R.string.dialog_tips_title))
                .setMessage("是否立即呼叫患者？确定后平台会立即呼叫患者，患者接通后会再次呼叫您，请您留意接听电话（电话为029开头）。")
                .setConfirm(getStringFromResource(R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    inquiryOrderViewModel.consultationCall(id,s,i)
                    it?.dismiss()
                }.create().show()

        }.show()





    }

    override fun initData() {
        LiveDataBus.get().with(REFUSE_RECEPTION, String::class.java)
            .observe(this) {
                //拒绝 转诊
                if (orderType == 1) getPrescribedList()
            }
        LiveDataBus.get().with(CLINICAL_RECEPTION, String::class.java)
            .observe(this) {
                //接诊
                if (orderType == 1 || orderType == 2) getPrescribedList()
            }

        //退诊成功
        inquiryOrderViewModel.finishLiveData.observe(this) {
            dismissLoading()
            if (it) {
                showToast("退诊成功")
                if (orderType == 2 || orderType == 3) getPrescribedList()
            }
        }
        //拒诊
        inquiryOrderViewModel.turnDownLiveData.observe(this) {
            dismissLoading()
            LiveDataBus.get().with(REFUSE_RECEPTION).postValue(REFUSE_RECEPTION)
        }
        //接诊成功
        inquiryOrderViewModel.receptionLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(CLINICAL_RECEPTION).postValue(CLINICAL_RECEPTION)
                LiveDataBus.get().with(SET_INDEX).postValue(SET_INDEX)
                inquiry?.let { details ->
                    if (details.consultationType == 1) {
                        goToChat( UserInfo(
                            details.patientWyyxAccId,
                            details.patientName,
                            details.patientAvatar
                        ), details.patientId )

                    }
                }
            }
        }
        inquiryOrderViewModel.orderLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                mAdapter.setData(it)
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding?.emptyView?.visible()
                } else {
                    mBinding?.emptyView?.gone()
                }
            } else {
                mBinding?.refreshLayout?.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mAdapter.addAll(it)
                } else {
                    mBinding?.refreshLayout?.setEnableLoadMore(false)
                }
            }
        }
        inquiryOrderViewModel.callLiveData.observe(this) {
            if (it) {
                showToast("正在为您呼叫患者，请稍后")
            }
        }
        showLoading()
        getPrescribedList()
    }

    private fun getPrescribedList() {
        inquiryOrderViewModel.getConsultationOrder(count = mPage, pageSize = 10, orderType)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getPrescribedList()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getPrescribedList()
    }
}